//
//  XJTieZiDetailView.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/6/7.
//  Copyright © 2018年 Tzyang. All rights reserved.
//  帖子详情View

#import "XJTieZiDetailView.h"

//view
#import "XJTieZiDetailHeaderView.h"
#import "XJTieZiDetailCell.h"

#import "XJYMTTieziDetailBottomView.h" //
#import "DKSKeyboardView.h" // 评论键盘


//model
#import "XJTieZiDetailModel.h"

//vendor
#import "UITableView+SDAutoTableViewCellHeight.h"



@interface XJTieZiDetailView()<UITableViewDelegate,UITableViewDataSource,DKSKeyboardDelegate,UIGestureRecognizerDelegate>

@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) XJTieZiDetailHeaderView *headerView;

/**评论数组*/
@property(nonatomic, strong) NSMutableArray *commentsArray;
@property(nonatomic, strong) XJTieZiDetailModel *detailModel;

@property(nonatomic, strong) XJYMTTieziDetailBottomView *bottomView;
@property(nonatomic, strong) DKSKeyboardView *commentKeyBoard; // 评论键盘

/**flag 用于判断是一级评论还是二级评论:默认是一级评论*/
@property (nonatomic, assign) BOOL firstLevelComment;
/**flag 记录当前点击的cell的 indexPath ,作用取出对应的model*/
@property (nonatomic, strong) NSIndexPath *selectedIndexPath;


@end

@implementation XJTieZiDetailView

#pragma mark - 一 初始化
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupVeiw];
    }
    return self;
}
- (void)setupVeiw{
    // 一 tableView
    
    CGRect tempTableViewFrame = self.bounds;
//    tempTableViewFrame.size.height = self.bounds.size.height - 64;
    self.tableView.frame = tempTableViewFrame;
    [self addSubview:self.tableView];
    
    // 设置区头
    self.tableView.tableHeaderView = self.headerView;
    
    
    // 底部 (点赞+ 评论)view
    [self addSubview:self.bottomView];
    self.bottomView.tieId = self.tieZiId;
    
    self.firstLevelComment  = YES; // 默认为YES
}

- (NSMutableArray *)commentsArray {
    if (!_commentsArray) {
        _commentsArray = [NSMutableArray array];
    }
    return _commentsArray;
}

#pragma mark - 二 lazy
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        
        _tableView.delegate  =self;
        _tableView.dataSource  =self;
        
        [_tableView registerClass:[XJTieZiDetailCell class] forCellReuseIdentifier:@"XJTieZiDetailCellId"];
        
        _tableView.tableFooterView = [UIView new];
        
        //给UITableView添加手势,作用:回收键盘
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] init];
        tapGesture.delegate = self;
        [_tableView addGestureRecognizer:tapGesture];
    }
    return _tableView;
}

- (XJTieZiDetailHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[XJTieZiDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 160)];
    }
    return _headerView;
}

- (XJYMTTieziDetailBottomView *)bottomView {
    if (!_bottomView) {

        _bottomView = [[XJYMTTieziDetailBottomView alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 64, KWidth, 64)];
        XJWeakSelf(self);
        
        //点击评论
        _bottomView.clickCommentButtonBlock = ^{
            XJLog(@"点击评论");
            weakself.firstLevelComment = YES; // 标记为一级评论 点击的是下面的评论按钮
            [weakself.commentKeyBoard ds_becomFirstResponder];
        };
    }
    return _bottomView;
}

// 评论键盘
- (DKSKeyboardView *)commentKeyBoard {
    if (!_commentKeyBoard) {
        _commentKeyBoard = [[DKSKeyboardView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 50)];
        _commentKeyBoard.delegate = self;
        [self addSubview:_commentKeyBoard];
    }
    return _commentKeyBoard;
}



#pragma mark -  四-1 UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.commentsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    XJTieZiDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XJTieZiDetailCellId"];
    
    XJTieZiDetailCommentModel *model = self.commentsArray[indexPath.row];
    cell.commentModel = model;

    [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
    
    
    
    XJWeakSelf(self);
    // 事件回调
    cell.tieziDetailCellDeleteCommentBtnBlock = ^(BtnType btnType) {
        
        self.selectedIndexPath = indexPath; // 标记选中的cell的indexPath
        switch (btnType) {
            case BtnTypeNoLogin:
                [JRToast showWithText:@"没有登录"];
                break;
            case BtnTypeDelete:
            {
//                [JRToast showWithText:@"调删除接口"];
                XJLog(@"%ld--%ld",indexPath.section,indexPath.row);
                
                XJTieZiDetailCommentModel *commentModel = self.commentsArray[indexPath.row];
                [weakself requestDeleteCommentWithCommentId:commentModel.detailCommentId];
            }break;
                
            case BtnTypeComment:
            {
//                [JRToast showWithText:@"调评论接口"];
                
                weakself.firstLevelComment = NO; // 标记为二级评论 点击的是cell上的评论按钮
                [weakself.commentKeyBoard ds_becomFirstResponder];
            } break;
            default:
                break;
        }
    };
    
    return cell;
}
#pragma mark -  四-2 UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return  [self cellHeightForIndexPath:indexPath cellContentViewWidth:KWidth tableView:self.tableView];
}







#pragma mark - 五-1 DKSKeyboardDelegate  评论键盘代理方法
//发送的文案
- (void)textViewContentText:(NSString *)textStr {
    if ([NSString isEmptyString:textStr]) {
        [JRToast showWithText:@"请输入内容"];
        return;
    }
 

    XJLog(@"firstLevelComment：%d",self.firstLevelComment);
    if (self.firstLevelComment) {
        XJLog(@"点击的是一级评论");
        [self requestFirstLevelCommentWithText:textStr];
    }else {
        XJLog(@"点击的是二级评论按钮");
        [self requestSecondLevelCommentWithText:textStr];
    }
    
    
    //    //    [self.dataAry addObject:textStr];
    //    //    [self.tableView reloadData];
    //    //    [self scrollToBottom];

}


#pragma mark - 五-2 UIGestureRecognizerDelegate 回收键盘
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    //收回键盘
    [[NSNotificationCenter defaultCenter] postNotificationName:@"keyboardHide" object:nil];
    //若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return YES;
}


#pragma mark - Private method

#pragma mark -  三 网络请求
- (void)requestTieziDetail {
    
    XJLog(@"%@",self.tieZiId);
    // 可能会炸。服务器返回的是NSNumber类型。未做处理。
    if ([NSString isEmptyString:self.tieZiId])  return;

    
//    NSDictionary *parDic = @{@"invitation_id":self.tieZiId,
//                             @"type":@"ymt"
//                             };
    NSString *customer_id = [XJUserModel xj_customId];
    if([NSString isEmptyString:customer_id]) return;
    
    NSDictionary *parDic = @{@"invitation_id":self.tieZiId,
                             @"type":self.type,
                             @"customer_id":customer_id
                             };
    [XJHttpTool requestInvitationDetailInfoWithDic:parDic successH:^(id responseObjc) {
        
                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObjc options:NSJSONWritingPrettyPrinted error:nil];
                NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                XJLog(@"%@",jsonStr);
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
            NSDictionary *infoDic = responseObjc[@"data"][@"invitation_info"];
            
            self.commentsArray = [XJTieZiDetailCommentModel mj_objectArrayWithKeyValuesArray:infoDic[@"invitation_comments"]];
            
            
            //这是时间戳需要单独转为时间
            NSString *createTimeStamp  = [NSString stringWithFormat:@"%@",infoDic[@"create_time"]];
           NSString *createTimeStr = [NSString timeStrFromTimeStamp:createTimeStamp];
            
            // 单独赋值:创建对象
            self.detailModel = [XJTieZiDetailModel new];
            self.detailModel.publish_time = createTimeStr;
            self.detailModel.publish_name = infoDic[@"publish_name"];
            self.detailModel.plain_content = infoDic[@"plain_content"];
            self.detailModel.click_count = infoDic[@"click_count"];
            self.detailModel.avator = infoDic[@"avatar"];
            self.detailModel.xjTieZiDetailModelId = [NSString stringWithFormat:@"%@",infoDic[@"id"]]; //评论接口请求参数 ✅
            
            
            NSString *timeStr = infoDic[@"publish_time"];
            //刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.headerView configureIcon:self.detailModel.avator name:self.detailModel.publish_name time:self.detailModel.publish_time content:self.detailModel.plain_content howHourAge:timeStr browseTimes:self.detailModel.click_count];
                
                [self.tableView reloadData];
            });
            
            
        }else {
            XJLog(@"%@",responseObjc);
            [JRToast showWithText:@"请求出错"];
        }
        
    } failH:^(NSError *error) {
        XJLog(@"%@",error);
    }];
}

// 外部调用 这个方法不能动:因为把网络请求放到了View层 找不到合适的时机调用网络请求，只能在外部 把对象创建好了之后 再 单独调用这个方法进行网络请求。
- (void)tieZiDetailViewRequestData{
    [self requestTieziDetail];
}


/**一级评论*/
- (void)requestFirstLevelCommentWithText:(NSString *)text{

    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    
    [parDic setValue:self.detailModel.xjTieZiDetailModelId forKey:@"invitation_id"];
    [parDic setValue:@"0" forKey:@"target_id"];
    [parDic setValue:@"1" forKey:@"target_customer"];
    [parDic setValue:text forKey:@"text"];
    [parDic setValue:@"1" forKey:@"level"];
    [parDic setValue:@"0" forKey:@"root_id"];
    [parDic setValue:@"1" forKey:@"target_type"];

    [XJHttpTool requestInvitationCommentWithDic:parDic succesH:^(id responseObjc) {
        XJLog(@"成功:%@",responseObjc);
        // 就返回一个数组:
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            XJTieZiDetailCommentModel *commentM = [XJTieZiDetailCommentModel mj_objectWithKeyValues:responseObjc[@"data"][@"invitation_comment"]];
            
            [self.commentsArray addObject:commentM];
            [self.tableView reloadData];
        }
        
    } failH:^(NSError *error) {
        XJLog(@"失败:%@",error);
    }];
}


/** 二级评论 */
- (void)requestSecondLevelCommentWithText:(NSString *)text {
    
//    {
//        "target_type": "0",
//        "target_id": "503",
//        "text": "办理",
//        "level": "2",
//        "invitation_id": "48",
//        "target_customer": "7",
//        "root_id": "503"
//    }
    
    XJTieZiDetailCommentModel  *commentM = self.commentsArray[self.selectedIndexPath.row];
    NSString *target_id = commentM.detailCommentId;
    NSString *customeId = commentM.customer_id;
    
    NSString *invitation_id = self.detailModel.xjTieZiDetailModelId;
    NSDictionary * parDic = @{@"target_type":@"0",
                              @"target_id":target_id,
                              @"text":text,
                              @"level":@"2",
                              @"invitation_id":invitation_id,
                              @"target_customer":customeId,
                              @"root_id":target_id
                              };
    
    [XJHttpTool requestInvitationCommentWithDic:parDic succesH:^(id responseObjc) {
//        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObjc options:NSJSONWritingPrettyPrinted error:nil];
//        NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//        XJLog(@"%@",jsonStr);
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
            [self requestTieziDetail]; // 零时救急写法。
        }
        
        
    } failH:^(NSError *error) {
        XJLog(@"失败:%@",error);
    }];
}


/**删除评论*/
- (void)requestDeleteCommentWithCommentId:(NSString *)commentId {
    
    [XJHttpTool requestInvitationDeleteCommentWithCommentId:commentId successH:^(id responseObjc) {
        XJLog(@"成功:%@",responseObjc);
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
            [self requestTieziDetail]; // 删除成功刷新数据
            
        }else {
            [JRToast showWithText:responseObjc[@"message"]];
        }
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}

@end
